import { useUserStore } from '@/stores/userStore';
import type { ApiResponse } from '@/types';
import axios from 'axios';

const http = axios.create({
  baseURL: '//localhost:3000',
  timeout: 5000,
});

// 请求拦截器
http.interceptors.request.use((config) => {
  const userStore = useUserStore();
  const token = userStore.token;
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const data = response.data as ApiResponse<any>;
    if (data.code >= 300 || data.code < 200) {
      ElMessage.error(data.message || '请求失败');
      return Promise.reject(data);
    }
    return data.data;
  },
  (error) => {
    ElMessage.error(error.message || '请求失败');
    return Promise.reject(error);
  },
);

export default http;
